# /usr/bin/python
# -*- coding:utf-8 -*-
import functools
import time



def logPrint(param):
    if callable(param):
        def wrapper(*args, **kw):
            print('%s function()' % (param.__name__,))
            param(*args, **kw)

        return wrapper

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print('%s %s():' % (param, func.__name__))
            return func(*args, **kw)

        return wrapper

    return decorator

def logged(msg ='', when='all'):
    def log(f, *args, **kargs):
        print('''
         called: functions:%s args: %r kargs: %r
    ''' % (f, args, kargs))

    def pre_logged(f):
        def wrapper(*args, **kargs):
            log(f, *args, **kargs)
            return f(*args, **kargs)

        return wrapper

    def post_logged(f):
        def wrapper(*args, **kargs):
            now = time()
            try:
                return f(*args, **kargs)
            finally:
                log(f, *args, **kargs)
                print("time delta:%s" % (time() - now))

        return wrapper

    def all_logged(f):
        def wrapper(*args, **kargs):
            now = time.time()
            print('>>> START => %s'%msg)
            # log(f, *args, **kargs)
            try:
                return f(*args, **kargs)
            finally:
                print('<<< END --  <%s'%msg+"> [time]:%.2fs " % (time.time() - now))
                # log(f, *args, **kargs)
                # print("time delta:%s" % (time() - now))

        return wrapper

    try:
        if when=='all':
            return all_logged
        else:
            return {"pre": pre_logged, "post": post_logged}[when]
    except KeyError as e:
        raise ValueError(e)('must be "pre" or "post"')


@logged(msg="这里say hello")
def hello(name):
    print("hello,", name)
    time.sleep(5)

if __name__ == "__main__":
    hello("world!")
